package com.swotxu.oldwebproject.redis.utils;

import com.swotxu.oldwebproject.redis.conf.RedisConfig;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 解析 redis.properties 中 redis配置
 *
 * @Date: 2021/3/24 0024 10:50
 * @Author: swotxu
 */
public class RedisPropertiesUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisPropertiesUtil.class);

    private static final String PROPERTIES_NAME = "/redis.properties";
    private static Properties pro;
    private static RedisConfig redisConfig;

    static {
        try {
            reload();
        } catch (IOException e) {
            LOGGER.error("Redis resource failed to load!", e);
        }
    }

    public static void reload() throws IOException{
        // ResourceBundle bundle = ResourceBundle.getBundle(PROPERTIES_NAME);
        InputStream in = RedisPropertiesUtil.class.getResourceAsStream(PROPERTIES_NAME);
        synchronized (RedisPropertiesUtil.class) {
            pro = new Properties();
            try {
                pro.load(in);
                init();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
    private static void init(){
        RedisConfig redisconf = new RedisConfig();

        JedisPoolConfig jedisPoolConf = new JedisPoolConfig();
        jedisPoolConf.setMaxIdle(getIntProperty(pro.getProperty("redis.maxIdle")));
        jedisPoolConf.setMaxWaitMillis(getIntProperty(pro.getProperty("redis.maxWait")));
        jedisPoolConf.setMaxTotal(getIntProperty(pro.getProperty("redis.maxActive")));

        redisconf.setConnectionConfig(jedisPoolConf);
        redisconf.setHost(pro.getProperty("redis.host").trim());
        redisconf.setPort(getIntProperty(pro.getProperty("redis.port")));
        redisconf.setPassword(pro.getProperty("redis.password").trim());
        redisconf.setDatabase(getIntProperty(pro.getProperty("redis.database")));
        redisconf.setTimeOut(getIntProperty(pro.getProperty("redis.timeOut")));
        redisconf.setSessionInactiveInterval(getIntProperty(pro.getProperty("redis.sessionInactiveInterval")));

        redisConfig = redisconf;

    }

    private static Integer getIntProperty(String param) {
        int result = 0;
        if (param != null) {
            result = Integer.valueOf(param.trim());
        }
        return result;
    }

    public static RedisConfig getRedisCofig() {
        return redisConfig;
    }

    public static String getSystemName() {
        return pro.getProperty("redis.systemName");
    }

    public static boolean isEnable() {
        return "Y".equalsIgnoreCase(pro.getProperty("redis.enable").trim());
    }

}
